<template>
  <div class="lifecycle-page">
    <h1>onBeforeUnmount 生命周期钩子</h1>
    
    <div class="lifecycle-card">
      <h2>什么是 onBeforeUnmount?</h2>
      <p>onBeforeUnmount 钩子在组件卸载前调用，此时组件实例依然完全可用。</p>
      <p>这是清理副作用（如定时器、事件监听器等）的理想时机。</p>
    </div>
    
    <div class="lifecycle-card">
      <h2>企业实践</h2>
      <p>在实际开发中，onBeforeUnmount的常见用途：</p>
      <ul>
        <li>清除定时器和计时器</li>
        <li>移除事件监听器</li>
        <li>取消网络请求</li>
        <li>销毁第三方库实例</li>
      </ul>
      <div class="code-example">
        <pre><code>
import { onBeforeUnmount } from 'vue'

export default {
  setup() {
    // 创建定时器
    const timer = setInterval(() => {
      console.log('定时器运行中...')
    }, 1000)
    
    // 添加事件监听
    const handleResize = () => console.log('窗口大小改变')
    window.addEventListener('resize', handleResize)
    
    // 在组件卸载前清理
    onBeforeUnmount(() => {
      // 清除定时器
      clearInterval(timer)
      
      // 移除事件监听
      window.removeEventListener('resize', handleResize)
      
      console.log('组件即将卸载，资源已清理')
    })
  }
}
        </code></pre>
      </div>
    </div>
    
    <div class="navigation">
      <router-link to="/updated" class="nav-button">上一个: onUpdated</router-link>
      <router-link to="/unmounted" class="nav-button">下一个: onUnmounted</router-link>
    </div>
  </div>
</template>

<script>
import { ref, onBeforeUnmount, onMounted } from 'vue'

export default {
  name: 'OnBeforeUnmountView',
  setup() {
    const timerId = ref(null)
    const tickCount = ref(0)
    
    onMounted(() => {
      // 设置一个定时器
      timerId.value = setInterval(() => {
        tickCount.value++
        console.log('定时器tick:', tickCount.value)
      }, 1000)
      
      console.log('定时器已启动')
    })
    
    onBeforeUnmount(() => {
      console.log('onBeforeUnmount 被调用')
      
      // 清除定时器
      if (timerId.value) {
        clearInterval(timerId.value)
        console.log('定时器已清除')
      }
    })
    
    return {
      tickCount
    }
  }
}
</script>

<style scoped>
.lifecycle-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

h1 {
  color: #3498db;
  text-align: center;
  margin-bottom: 30px;
}

.lifecycle-card {
  background-color: #f8f9fa;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

h2 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.code-example {
  background-color: #2c3e50;
  color: #ecf0f1;
  padding: 15px;
  border-radius: 5px;
  overflow-x: auto;
  margin: 15px 0;
}

pre {
  margin: 0;
}

ul {
  padding-left: 20px;
}

li {
  margin-bottom: 8px;
}

.navigation {
  display: flex;
  justify-content: space-between;
  margin-top: 30px;
}

.nav-button {
  display: inline-block;
  padding: 10px 20px;
  background-color: #3498db;
  color: white;
  text-decoration: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}

.nav-button:hover {
  background-color: #2980b9;
}
</style>